import mintPicker from '@/pages/releaseHouse/template/mintPicker.vue';
import houseingAllocation from '@/pages/releaseHouse/template/housingAllocation.vue';
import payforType from './template/payforType.vue';

import communityMap from '@/pages/houseAmap/houseAmap.vue';
// 户型
import houseType from '@/pages/houseList/template/houseType.vue';
// 其他费用
import otherFee from '@/pages/releaseHouse/template/otherFee.vue';
import MoUpload from '@/components/upload.vue';

import {mapState} from 'vuex';    //vuex
import {MessageBox,Toast} from 'mint-ui';

import VueAMap from 'vue-amap';
let amapManager = new VueAMap.AMapManager();

export default {
  name:'releaseHouse',
  data:() => ({
    house:'',     //房源信息
    slots: [],
    valueKey:'',                //mintUIpicker显示关键词
    isMintPicker:false,
    mintPickerType:'',        //弹窗的类型，朝向、装修。。。

    rentTypeValue:'',    //租住类型
    buildName:'',               //小区名称
    adcode:'',        //地图编码
    communityPoi:'',            //小区地图相关信息
    showCommunityMap:false,     //是否显示地图
    floor:'',                  //楼层
    floorTotal:'',              //总楼层
    houseTypeValue:'',          //房屋类型
    roomNum:'',                 //房间数量
    hallNum:'',                 //厅数量
    washroomNum:'',             //卫生间数量
    orientationValue:'',        //朝向
    decorateValue:'',           //装修
    configIds:'',               //房源配置ID数组,逗号','分隔 string
    chooseHouseActName:'',      //房源配置名称显示
    scale:'',                   //面积
    address:'',                 //地址
    buildingNum:'',             //楼栋号
    rentMoney:0,                //房租       长租
    rentDayMoney:0,             //每晚租金    短租
    payforType:'',              //付款方式
    choosePayforType:'',        //存储付款方式对象
    otherFeeIds:[],             //其他费用,逗号','分隔
    otherFeeValue:[],           //存储选中的费用对象
    fees:'',                    //费用金额 分,,逗号','分隔
    houseTag:[],                //房源标签，逗号分隔，显示用
    description:'',             //房源描述

    isPickerCity:false,
    isPickerDistrict:false,

    dialogImageUrl: '',
    dialogVisible: false,
    popupVisible:false,         //房屋配置选择
    popupPayfor:false,          //付款方式选择
    isHouseType:false,          //户型
    isOtherFee:false,           //其他费用

    uploadToken:'',           //七牛token
    thumbnail:[],             //七牛返回的图片地址

    phoneBalbum:[],           //相册
    selected:[1],
    albumIds:[],              //存储选中的相册id


  }),
  components:{
    mintPicker,
    houseingAllocation,
    payforType,
    communityMap,
    houseType,
    otherFee,
    MoUpload,
  },
  methods: {

    // 选择小区，进入地图查找
    searchCommunity() {
      this.showCommunityMap = true;
    },
    communityMapEvent(data){
      console.log(data);
      this.showCommunityMap = false;
      this.communityPoi = data.placeLi;
      this.buildName = data.placeLi.name;
      this.address = data.placeLi.address;
      this.adcode = data.placeLi.adcode;
    },
    // 租住类型
    rentTypeCK(){
      this.isMintPicker = true;  //弹窗
      this.mintPickerType = '租赁类型';
      this.slots=[{
        flex: 1,
        values:[{
          text:'业主长租',
          rentType:1,
        },{
          text:'业主短租',
          rentType:2,
        }],
        className: 'slot1',
        textAlign: 'center'
      }];
      this.valueKey = 'text';
    },
    // 户型
    houseTypeCK(){
      this.isHouseType = true;  //弹窗
    },
    houseTypeEvent(data) {
      this.isHouseType = false;  //弹窗
      console.log(data);
      this.roomNum = data[0];
      this.hallNum = data[1];
      this.washroomNum = data[2];
      this.houseTypeValue = data[0]+data[1]+data[2];
    },
    // 选择朝向
    orientationCK(){
      var that = this;
      that.mintPickerType = '朝向';
      network.get(configUrl.HOUSETOWARD_URL,'',function(res){
        console.log(res);
        var towardValue = res.dataList;
          that.isMintPicker = true;  //弹窗
          that.slots=[{
            flex: 1,
            values:towardValue,
            className: 'slot1',
            textAlign: 'center',
            defaultIndex:0,
          }];
          that.valueKey = 'towardName';
        },function(err){
        console.log(err);
      });
    },
    // 选择装修
    decorateCK(){
      var that = this;
      that.mintPickerType = '装修';
      network.get(configUrl.HOUSEDECORATE_URL,'',function(res){
        console.log(res);
        var decorateValue = res.dataList;
        that.isMintPicker = true;  //弹窗
        that.slots=[{
          flex: 1,
          values:decorateValue,
          className: 'slot1',
          textAlign: 'center',
          defaultIndex:0,
        }];
        that.valueKey = 'decorateName';
      },function(err){
        console.log(err);
      });

    },
    // 房屋配置
    housingAllocation(){
      this.popupVisible = true;
    },
    houseAllocation(data){
      this.configIds = data.chooseHouseAct.join(',');
      this.chooseHouseActName = data.chooseHouseActName.join(',');
        // console.log(this.configIds);
      this.popupVisible = false;
    },

    // 付款方式
    payforLi(){
      this.popupPayfor = true;
    },
    chooseBtn(data){
      console.log(data);
      this.payforType = data.choosePayforType.payTypeName;
      this.choosePayforType = data.choosePayforType;
      this.popupPayfor = false;
    },
    // 其他费用
    addOtherFee() {
      let that = this;
      that.isOtherFee = true;
      that.mintPickerType = '其他费用';
      network.get(configUrl.GETOTHERFEE_URL,'',function(res){
        console.log(res);
        var dataList = res.dataList;
        that.isMintPicker = true;  //弹窗
        that.slots=[{
          flex: 1,
          values:dataList,
          className: 'slot1',
          textAlign: 'center',
          defaultIndex:0,
        }];
        that.valueKey = 'otherFeeName';
      },function(err){
        console.log(err);
      });
    },
    mintPickerBtn(data){
      console.log(data);
      this.isMintPicker = false;  //关闭弹窗
      let that = this;
      if(data.chooseBtn){

        let mintPickerType = that.mintPickerType;
        switch (mintPickerType) {
          case '城市':
            that.cityList = data.mintChooseValue;
            break;
          case '区县':
            that.districtList = data.mintChooseValue;
            break;
          case '租赁类型':
            that.rentTypeValue = data.mintChooseValue;
            break;
          case '朝向':
            that.orientationValue = data.mintChooseValue;
            break;
          case '装修':
            that.decorateValue = data.mintChooseValue;
            break;
          case '其他费用':
            // console.log(that.otherFeeValue);
            let mintChooseValue = data.mintChooseValue;
            mintChooseValue.value = '';
            that.$nextTick( () => {
              that.otherFeeValue.push(mintChooseValue);
              let otherFeeIds = [];
              for (var i = 0; i < that.otherFeeValue.length; i++) {
                otherFeeIds.push(that.otherFeeValue[i].otherFeeId);
              }
              that.otherFeeIds = otherFeeIds;
            });

            break;
          default:
            break;
        }
      }

    },
    // 添加房源标签
    addHouseTag(){
      let that = this;
      let houseTag = that.houseTag;
      let lng = houseTag.length || 0;
      console.log(houseTag);
      // for (var i = 0; i < lng+1; i++) {
        that.houseTag.push({
          tagId:(lng+1),
          tag:''
        })
      // }
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 删除其他费用选项
    removeOtherFee(index){
      let that = this;
      that.$nextTick( () => {
        that.otherFeeValue.splice(index,1);
        that.otherFeeIds.splice(index,1);
      });
    },
    // 删除房源标签
    removeHouseTag(index) {
      let that = this;
      that.$nextTick( () => {
        that.houseTag.splice(index,1);
      });
    },

    // 七牛图片上传处理
    uploadComplete(status, result, uploadResult, flag) {
       // var addr = 'http://opf2ucy0n.bkt.clouddn.com/';
       console.log(uploadResult);
      console.log(result);
        if (status == 200) { //
            this.thumbnail.push(uploadResult.link+'/'+result.key); //七牛域名 + 返回的key 组成文件url
            this.albumIds.push(1);
            this.selected.push(1);
        } else {
            //失败处理
        }
    },
    // 房屋图片删除
    deleteUploadImg(index) {
      let that = this;
      let thumbnail = that.thumbnail;
      thumbnail.splice(index,1);
      that.albumIds.splice(index,1);
    },
    // 选择相册
    chooseMedicine(event) {
      console.log(event);
      let index = event.target.dataset.index;
      let albumId = this.selected[index];
      this.albumIds[index] = albumId;

      // console.log(this.albumIds);
    },
    // 确认
    submitRelease() {
      let that = this;
      let userInfo = JSON.parse(window.localStorage.getItem('userInfo'));
      let rentTypeValue = that.rentTypeValue;
      if(rentTypeValue==''){
        Toast('未选择租赁类型');
        return false;
      }
      let communityName = that.buildName;
      if(communityName==''){
        Toast('未选择小区名称');
        return false;
      }
      let floor = that.floor;
      if(floor==''){
        Toast('请填写楼层');
        return false;
      }
      let floorTotal = that.floorTotal;
      if(floorTotal==''){
        Toast('请填写总楼层');
        return false;
      }
      let roomNum = parseInt(that.roomNum);
      let hallNum = parseInt(that.hallNum);
      let washroomNum = parseInt(that.washroomNum);
      if (roomNum=='' || hallNum=='' ||washroomNum=='') {
        Toast('请选择户型');
        return false;
      }
      let houseTowardId = that.orientationValue.houseTowardId;
      if (houseTowardId=='') {
        // Toast('请选择朝向');
        // return false;
        houseTowardId = that.house.houseTowardId;
      }
      let decorateId = that.decorateValue.decorateId;
      if (decorateId=='') {
        // Toast('请选择装修类型');
        // return false;
        decorateId = that.house.decorateId;
      }
      let houseArea = that.scale;
      if (houseArea=='') {
        Toast('请填写房源面积');
        return false;
      }
      let configIds = that.configIds; //房源配置id

      let address = that.address;
      if (address=='') {
        Toast('请填写房屋地址');
        return false;
      }
      let buildingNum = that.buildingNum;
      if (buildingNum=='') {
        Toast('请填写楼栋号');
        return false;
      }
      let rentType = rentTypeValue.rentType;
      let rentMoney = 0;
      let rentDayMoney = 0;
      let payTypeId = 0;
      if(rentType==1){    //长租的情况
        rentMoney = parseFloat(that.rentMoney);   //元
        that.rentDayMoney = 0;
        if (rentMoney==0) {
          Toast('请输入房屋租金');
          return false;
        }

        payTypeId = that.choosePayforType.payTypeId;
        if (that.choosePayforType=='') {
          Toast('请选择付款方式');
          return false;
        }

      }else if(rentType==2){      //短租的情况
        rentDayMoney = parseFloat(that.rentDayMoney);   //元
        console.log(rentDayMoney);
        that.rentMoney = 0;
        if (rentDayMoney==0) {
          Toast('请输入房屋租金');
          return false;
        }
        payTypeId = 0;
      }

      let otherFeeIds = that.otherFeeIds.join(','); //其他费用id,隔开
      let otherFeeValue = that.otherFeeValue;   //其他费用对象
      console.log(otherFeeValue);
      let otherFees = [];    //存储费用金额
      for (var i = 0; i < otherFeeValue.length; i++) {
        otherFees.push(otherFeeValue[i].fee);
      }
      let fees = otherFees.join(',');
      // console.log(fees);

      let houseTagObj = that.houseTag;   //房源标签
      let houseTagTxt = [];           //房源标签名称
      for (var i = 0; i < houseTagObj.length; i++) {
        if (houseTagObj[i].tag=='') {
          Toast('您有添加的房源标签未命名');
          return false;
        }
        houseTagTxt.push(houseTagObj[i].tag);
      }
      let houseTag = houseTagTxt.join(',');

      let description = that.description;

      let housePics = that.thumbnail.join(',');
      let albumIds = this.albumIds.join(',');

      let lat = that.communityPoi.lat;
      let lng = that.communityPoi.lng;
      let releaseParam = {
        // token:userInfo.token,
        houseId:that.house.houseId,
        rentType:rentTypeValue.rentType,
        communityName:communityName,
        floor:floor,
        floorTotal:floorTotal,
        roomNum:roomNum,
        hallNum:hallNum,
        washroomNum:washroomNum,
        houseTowardId:houseTowardId,
        decorateId:decorateId,
        houseArea:houseArea,
        configIds:configIds,
        adcode:that.adcode,
        address:address,
        buildingNum:buildingNum,
        rentMoney:rentMoney,
        rentDayMoney:rentDayMoney,
        payTypeId:payTypeId,
        otherFeeIds:otherFeeIds,
        fees:fees,
        houseTag:houseTag,
        description:description,
        housePics:housePics,
        albumIds:albumIds,      //相册id
        lat:lat,
        lng:lng,
      }
      network.post(configUrl.EDITHOUSE_URL,releaseParam,function(res){
        // console.log(res);
        if(res.code==401) {
          reLoginWX();
        }else{
          if (that.house.auditState==2) {
            Toast('房源编辑成功');
            that.$router.go(-1);
          }else {
            MessageBox.alert('编辑房源成功,等待后台审核~').then(action=>{
              that.$router.go(-1);
            })
          }

        }

      },function(err) {
        console.log(err);
      });
    }
  },
  mounted() {
    //do something after mounting vue instance
    let that = this;
    let houseId = that.$route.query.houseId;
    console.log(houseId);
    let houseParam = {
      houseId:houseId
    }
    // 通过houseid获取对应的房源信息
    that.$ajax.get(configUrl.LANDLORDHOUSEDETAIL_URL,{
      params:houseParam
    }).then(res=>{
      let editData = res.data.data;
      let house = editData.house;
      that.house = house;
      console.log(house);
// Object.keys(this.body).forEach(key => this.body[key] = res.data[key])

      let housePicList = editData.housePicList;   //房屋图片
      // 租住类型
      that.rentTypeValue = {
        text:house.rentTypeName,
        rentType:house.rentType
      }
      that.buildName = house.communityName;
      that.floor = house.floor;
      that.floorTotal = house.floorTotal;
      that.roomNum = house.roomNum+'室';
      that.hallNum = house.hallNum+'厅';
      that.washroomNum = house.washroomNum+'卫';
      that.houseTypeValue = house.roomNum+'室'+house.hallNum+'厅'+house.washroomNum+'卫';
      // that.houseInfo = res.data.house;
      that.scale = house.houseArea;
      that.address = house.address;
      that.buildingNum = house.buildingNum;
      that.description = house.description;
      that.rentMoney = house.rentMoney/100;
      that.rentDayMoney = house.rentDayMoney/100;

      that.adcode = editData.adcode;
      that.communityPoi = {
        buildName:house.communityName,
        address:house.address,
        lat:house.lat,
        lng:house.lng
      }
      that.orientationValue = {
        towardName:editData.towardName,
        houseTowardId:house.houseTowardId
      }
      that.decorateValue = {
        decorateName:editData.decorateName,
        decorateId:house.decorateId
      }

      that.houseTag = editData.houseTagList;   //房源标签
      for (var i = 0; i < editData.houseTagList.length; i++) {
        that.houseTag[i].tagId = i+1;
      }
      let houseRentConfigList = editData.houseRentConfigList;        //房源配置
      console.log(houseRentConfigList);
      let chooseHouseActName = [],configIds = [];
      for (var i = 0; i < houseRentConfigList.length; i++) {
        chooseHouseActName[i] = houseRentConfigList[i].configName;
        configIds[i] = houseRentConfigList[i].configId;
      }
      that.chooseHouseActName = chooseHouseActName.join(',');
      that.configIds = configIds.join(',');

      // 房源费用
      that.otherFeeValue = editData.houseOtherFeeList;

      that.thumbnail = housePicList;
      let album = [],houseimg=[];
      for (var i = 0; i < housePicList.length; i++) {
          houseimg[i] = housePicList[i].housePic;   //图片
          album[i] = housePicList[i].albumId;     //相册i
      }
      that.thumbnail = houseimg;
      that.albumIds = album;
      that.selected = album;
    }).catch(error=>{
      console.log(error);
    })

    // 获取房源相册列表
    network.get(configUrl.PHONEALBUM_URL,'',function(res){
      console.log(res);
      that.phoneBalbum = res.dataList;
    },function(err){
      console.log(err);
    });
  },
  computed:{
    //这里的三点叫做 : 扩展运算符
    ...mapState({
      token:state=>state.login.token
      // 相当于
      //show(){
      //     return this.$store.state.dialog.show;
      // }
    }),
  },
}
